package com.xhl.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Calendar;
import java.util.Map;

/**
 * 使用 com.auth0 封装的jwt
 * @Author CazCen
 * @Date 2021/12/1 11:37
 */
public class JWTUtils {
    private static final Logger logger = LoggerFactory.getLogger(MakeRSAUtil.class);
    private static final String TOKEN_SECRET = "token!@tea@google.com!126.com@163.com@!";

    /**
     * 生成token
     * @param map 传入 payload
     * @return 返回token
     */
    public static String getToken(Map<String,String> map){
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });

        Calendar instance = Calendar.getInstance();
        //24小时过期
//        instance.add(Calendar.HOUR,24);
        //1天过期
        instance.add(Calendar.DATE,1);
        builder.withExpiresAt(instance.getTime());
        String signToken = builder.sign(Algorithm.HMAC256(TOKEN_SECRET));
        return signToken;
    }

    /**
     * 验证token
     * @param token
     * @return
     */
    public static void verify(String token){
        JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).build().verify(token);
    }

    /**
     * 获取token中的payload
     * @param token
     * @return
     */
    public static DecodedJWT getTokenPayload(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).build().verify(token);
        return verify;
    }

    
}
